// pages/buy-record/buy-record.js
const api = require("../../server/Api.js");
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    curPage: 1,
    pageSize: 20,
    hasMore: true,
    spuId: "",
    total: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    this.setData({
      spuId: options.id
    })
    this.refreshData();
  },


  //下拉啊刷新
  onPullDownRefresh: function() {
    this.refreshData();
  },

  //刷新列表
  refreshData: function() {
    // tt.showNavigationBarLoading();
    var that = this;
    this.setData({
      hasMore: true,
    })
    this.queryOrderList(1, this.data.pageSize);
  },

  //上拉加载
  onReachBottom: function() {
    console.log(this.data.hasMore)
    if (this.data.hasMore == false) return;
    // tt.showNavigationBarLoading();
    let page = this.data.curPage + 1;
    this.queryOrderList(page, this.data.pageSize);
  },

  //分页查询订单
  queryOrderList: function(page, pageSize) {
    let that = this;
    let prams = {
      pageSize: that.data.pageSize,
      pageNumber: page,
      spuId: that.data.spuId
    };
    console.log(prams)
    api.orderBuyList(prams).then(res => {
      //请求成功
      that.querySuccess(res, page)
      tt.stopPullDownRefresh();
    }).catch(msg => {
      tt.stopPullDownRefresh();
      var message = typeof msg == "string" ? msg : msg.message;
      app.showToast(message);
    })
  },

  //查询成功
  querySuccess: function(res, curPage) {
    let that = this;
    let records = res.records;
    let maxPage = parseInt(res.pages);
    var datas = curPage == 1 ? [] : this.data.items;
    for (let i = 0; i < records.length; i++) {
      records[i].created_time = app.getBuyTime(records[i].created_time)
    }
    if (records) {
      datas = datas.concat(records);
    }
    that.setData({
      hasMore: maxPage > curPage,
      items: datas,
      curPage: curPage,
      total: res.total
    })
  },
})